"""
客户端Socket通信模块
"""
import socket
import json
import threading
import logging
from config import SERVER_HOST, SERVER_PORT, CLIENT_RECONNECT_INTERVAL

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class ClientSocket:
    def __init__(self):
        self.socket = None
        self.client_id = None
        self.connected = False
        self.reconnect_thread = None
        self.running = False

    def connect(self, username, password, callback=None):
        """连接到服务器"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((SERVER_HOST, SERVER_PORT))
            
            # 发送登录信息
            login_message = {
                'action': 'login',
                'username': username,
                'password': password
            }
            self.socket.send(json.dumps(login_message).encode('utf-8'))
            
            # 接收响应
            response = self.socket.recv(1024).decode('utf-8')
            result = json.loads(response)
            
            if result.get('status') == 'success':
                self.client_id = result.get('client_id')
                self.connected = True
                self.running = True
                
                # 启动心跳线程
                self.start_heartbeat()
                
                if callback:
                    callback(True, "登录成功")
                logger.info("连接服务器成功")
                return True
            else:
                self.socket.close()
                if callback:
                    callback(False, result.get('message', '登录失败'))
                return False
                
        except Exception as e:
            logger.error(f"连接服务器失败: {e}")
            if callback:
                callback(False, f"连接失败: {str(e)}")
            return False

    def start_heartbeat(self):
        """启动心跳线程"""
        def heartbeat():
            while self.running and self.connected:
                try:
                    if self.socket:
                        message = {'action': 'heartbeat'}
                        self.socket.send(json.dumps(message).encode('utf-8'))
                        threading.Event().wait(30)  # 每30秒发送一次心跳
                except Exception as e:
                    logger.error(f"心跳发送失败: {e}")
                    self.connected = False
                    break

        heartbeat_thread = threading.Thread(target=heartbeat)
        heartbeat_thread.daemon = True
        heartbeat_thread.start()

    def disconnect(self):
        """断开连接"""
        self.running = False
        self.connected = False
        if self.socket:
            try:
                self.socket.close()
            except:
                pass
        logger.info("已断开连接")

    def is_connected(self):
        """检查是否已连接"""
        return self.connected and self.socket is not None

